var statusResult = "2"
var type = true  
var onceRequestTAG = false;  // 判断是否可查字典表
if (sessionStorage.getItem('resourceRegistrationAudit_curr') != null) {
    sessionStorage.setItem('resourceRegistrationAudit_curr',1)
}
var tableData = []
var timesDate = getFamtterTimer () 
function saveTableAudit() {
    var checkURL;
    // 1   部门管理员   2  系统管理员
    if(userRole == "1"){
        checkURL = modelURL + "apply/approvalResourceList"
    }else if(userRole == "2"){
        checkURL = modelURL + "apply/admimApprovalResourceList"
    }
    let results = sendAjax(checkURL, "POST", {
        userno: portaluserno
    });  
    if (results.code == 200 ) {
        tableData = results.data.data;
    } else {
        layer.msg('获取失败')
    }
    tables ()  
    let resultsData = results.data.data
    let waitCountNum = 0
    for (let i = 0 ;i<resultsData.length;i++) {
        if (resultsData[i].STATUS == '1') {
            waitCountNum ++ 
        } 
    }
    $('#allCount').html(tableData.length + '个') 
    $('#waitCount').html(waitCountNum + '个') 
    $('#Count').html(tableData.length - waitCountNum  + '个') 
    table.on('tool(audit_table)', function (obj) { 
        if (obj.event == 'audits') {  
            //审核
            $('#auditsDivH3').html(obj.data.NAME)
            $('#applicant').val(obj.data.USERNAME) 
            let times = formatDate(obj.data.APPLY_TIME)
            $('#applicantTime').val(times) 
            $('#applyReason').val(obj.data.APPLY_REASON);
            $('#authorizationTime').val('2099-09-15 10:11:12') 
            layer.open({
                type: 1,
                title: "审核",
                shadeClose: true,
                content: $('#auditsDiv'),
                end: function (res) {
                    $("#auditsDiv").css("display", 'none');
                }
                ,btn: ['确定', '取消']
                ,yes: function(index,layero){ 
                    if ($('#authorizationReason').val() != '') {
                        type = true 
                    } 
                    let params = [
                        {
                            id:obj.data.ID,
                            status:statusResult,
                            checkTime:timesDate,
                            checkPerson: $('#applicant').val(),
                            checkInfo:$('#authorizationReason').val()
                        }
                    ]  
                    if (type) { 
                        // maps: [{"checkTime":"2021-9-17 16:32:32","checkPerson":"管理员","checkResult":"1","myId":"ddFDbDEA2fDa40EB8Bd388edC55DBCe4","checkInfo":"123","TREEID":"c45d5db988514740829c05d9c2e98b80","ZYLX":"3"}]
                        let results = sendAjax(modelURL + "apply/approvalResource", "POST", {
                            id:obj.data.ID,
                            status:statusResult,
                            approvalReason:$('#authorizationReason').val()
                        });  
                        if (results.code == 200 ) { 
                            layer.msg(results.msg) 
                            saveTableAudit () 
                        } else {
                            layer.msg('获取失败')
                        } 
                    }  else {
                        layer.msg('请填写审核意见') 
                    }
                    layer.close(index); 
                    $('#authorizationReason').val("")
                }
                ,btn2: function(index, layero){
                    layer.close(index); 
                }
            });
        } else if (obj.event == 'auditRecords') { 
            //查看审核记录
            var recordingData;
            let results = sendAjax(modelURL + "apply/getResourceUsedApprovals", "POST", {
                userNo:portaluserno,
                id:obj.data.ID
            });  
            if (results.code == 200 ) { 
                recordingData = results.data;
            } else {
                layer.msg('获取失败')
            }
            $('#auditRecordsH3').html(recordingData[0].name)
            $('#auditRecordsTime').html(formatDate(recordingData[0].approvalTime))  
            $('#auditRecordsYJ').html(recordingData[0].approvalReason)  
            var checkResultTxt;
            if(recordingData[0].applyStatus == "2"){
                checkResultTxt = "审核通过"
            }else if(recordingData[0].applyStatus == "3"){
                checkResultTxt = "审核未通过"
            }
            $('#auditRecordsJL').html(checkResultTxt);
            layer.open({
                type: 1,
                title: "审核记录",
                shadeClose: true,
                content: $('#auditRecordsDiv'),
                area:["600px"],
                end: function (res) {
                    $("#auditRecordsDiv").css("display", 'none');
                },
                btn: ['取消']
                ,yes: function(index,layero){ 
                    layer.close(index); 
                }
            });
        } else if (obj.event == 'browse') {
            var resourceId = obj.data.RESOURCEID;
            window.open("/MapServer/Portal/layerViewer.html?id=" + resourceId);
        } else if (obj.event == 'download') {

        } else if (obj.event == 'call') { 
            $('#usedDivH3').html(obj.data.NAME);
            $("#usedApplyPerson").val(obj.data.USERNAME);
            $("#usedApplyTime").val(formatDate(obj.data.APPLY_TIME));
            $("#usedApplyReason").val(obj.data.APPLY_REASON);
            $('#usedAddress').val(obj.data.PROXYADDRESS);
            layer.open({
                type: 1,
                title: "调用",
                shadeClose: true, //点击遮罩关闭
                content: $("#usedDiv"),
                btn: ['关闭'],
                yes: function(index, layero) {
                    layer.close(index);
                }
            });
        }
    }) 
    table.on('toolbar(audit_table)',function (obj) {
        if (obj.event == 'btn_search') {
            let timeNum = $('#ipt_date').val()
            let startTime = $.trim(timeNum.substring(0,10));
            let endTime = $.trim(timeNum.substring(13)); 
            let num 
            if ($('#resourceType').val() == 'arcgis服务') num = 1
            if ($('#resourceType').val() == '地图服务') num = 3
            if ($('#resourceType').val() == '图件服务') num = 4
            var searchURL;
            // 1   部门管理员   2  系统管理员
            if(userRole == "1"){
                searchURL = modelURL + "apply/approvalResourceList"
            }else if(userRole == "2"){
                searchURL = modelURL + "apply/admimApprovalResourceList"
            }
            let results = sendAjax(searchURL, "POST", { 
                name:$('#applicationName').val(),
                userno:portaluserno,
                zylx:num,
                startTime:startTime,
                endTime:endTime,
                applyPerson:$('#theApplicant').val()
            });   
            if (results.code == 200) { 
                sessionStorage.setItem('resourceRegistrationAudit_curr',1) 
                tableData = results.data.data
                tables () 
            }else{
                layer.msg("检索失败",{icon:5})
            }
        } else if (obj.event == 'btn_reset') { 
            sessionStorage.setItem('resourceRegistrationAudit_curr',1) 
            $('#reviewType').val('')
            $('#resourceType').val('') 
            $('#ipt_date').val('') 
            $('#theApplicant').val('') 
            $('#applicationName').val('') 
            saveTableAudit () 
        }
    })
} 
function resultFunction (obj) { 
    let results
    results = sendAjax(modelURL + "/apply/getApplyInfo", "POST", {
        id: obj.data.ID
    }); 
    return results
}  
// 时间戳转换时间函数 
function getYMDHMS (timestamp) {
    let time = new Date(timestamp)
    let year = time.getFullYear()
    const month = (time.getMonth() + 1).toString().padStart(2, '0')
    const date = (time.getDate()).toString().padStart(2, '0')
    const hours = (time.getHours()).toString().padStart(2, '0')
    const minute = (time.getMinutes()).toString().padStart(2, '0')
    const second = (time.getSeconds()).toString().padStart(2, '0')

    return year + '-' + month + '-' + date + ' ' + hours + ':' + minute + ':' + second
}
// 时间排序
function creatCompare(propertyName) {
    return function (obj1, obj2) {
        var value1 = obj1[propertyName];
        var value2 = obj2[propertyName];
        if (value1 > value2) {
            return -1
        } else if (value1 < value2) {
            return 1
        } else {
            return 0
        }
    }
}
function tables () {
    var name =  $('#reviewType').val()
    var dateTime =  $('#ipt_date').val()
    var theApplicantName =  $('#resourceType').val() 
    var theApplicant = $('#theApplicant').val() 
    var applicationName = $('#applicationName').val() 
    tableData.sort(creatCompare("APPLY_TIME"))
    var newTableData = tableData.map(item => { 
        return Object.assign({},item,{
            applyTime:getYMDHMS(item.APPLY_TIME)
        })
    })
    table.render({
        elem: '#audit_table',
        data: newTableData,
        toolbar:true, 
        toolbar:'#headerDiv',
        defaultToolbar:[],
        page: {
            limit:20,
            curr:sessionStorage.getItem('resourceRegistrationAudit_curr') ? sessionStorage.getItem('resourceRegistrationAudit_curr') : 1
        }, 
        done:function (res,curr,count) {
            sessionStorage.setItem('resourceRegistrationAudit_curr',curr)
            $("[data-field = 'NAME']").children().each(function () {
                if($(this).text() != "资源名称"){
                    $(this).addClass("linkTabTxt");
                }
            });
        }
        ,cols: [
            [ //表头
                {
                    type: 'numbers',
                    title: '序号',
                    sort: true,
                    width: 80,
                    align: "center"
                }, {
                    field: 'NAME',
                    title: '资源名称',
                    align: "center"
                }, {
                    title: '资源类型',
                    align: "center",
                    toolbar: '#typeLX',
                }, {
                    field: 'USERNAME',
                    title: '申请人',
                    align: "center"
                },{
                    field: 'applyTime',
                    title: '申请时间',
                    align: "center"
                },{
                    field: 'APPLY_REASON',
                    title: '申请理由',
                    align: "center"
                }, {
                    field: 'DANGQIAN',
                    title: '当前权限',
                    toolbar: '#currentPermissions',
                    align: "center"
                }, {
                    field: 'permission',
                    title: '操作',
                    toolbar: '#permissionAuditDiv',
                    align: "center"
                }
            ]
        ]
    }); 
    if (name != undefined || dateTime != undefined || theApplicantName != undefined || theApplicant != undefined || applicationName != undefined ) {
        $('#reviewType').val(name)
        $('#ipt_date').val(dateTime)
        $('#resourceType').val(theApplicantName) 
        $('#theApplicant').val(theApplicant) 
        $('#applicationName').val(applicationName) 
        layui.form.render('select')
    }
    laydate.render({
        elem: '#ipt_date'
        , type: 'date'
        , range: true
    }); 
    $('.layui-table-cell').click(function (e) {
        let text = e.target.innerText
        let currentData = null
        newTableData.map(item => {
            if (text == item.NAME) {
                currentData = item
                return
            }
        })
        if (currentData != null) {
            // getArcgisLayersInfoByGuid(String guid) arcgis服务  RESOURCEID
            // /resource/getResourceByGuid guid  图鉴服务 地图服务 
            let results = null
            if (currentData.ZYLX == 1 || currentData.ZYLX == 2) { 
                results = sendAjax(modelURL + "resource/getArcgisLayersInfoByGuid", "POST", {
                    guid: currentData.RESOURCEID
                });
                let data = results.data 
                for (var key in data) {
                    data = data[key];
                    break;
                }
                var isqueryVal;
                if (data.ISQUERY == "是" || data.ISQUERY == "1") {
                    isqueryVal = "是";
                } else {
                    isqueryVal = "否";
                }
                if (!onceRequestTAG) {
                    fillLayerDropdown('ipt_form_select',data);
                }
                //地图服务数据表单回显
                form.val('MapServiceBasicdataForm', {
                    "LAYERALIAS": data.LAYERALIAS,
                    // "COMPANY": data.COMPANY,
                    // "SPATIAL": data.SPATIAL,
                    // "SERVICESTYPE": data.SERVICE_CATEGORY,
                    // "RESOURCEPOSITION": data.POSITION,
                    "ADDRESS": data.ADDRESS,
                    // "ID": data.ID,
                    "STYLE": data.STYLE,
                    "POSITION": data.LAYERPOSITION,
                    "PRJ": data.PRJ,
                    "PARAMETERS": data.PARAMETERS,
                    // "SERVICETYPE": data.SERVICETYPE,
                    // "SOURCE": data.SOURCE,
                    // "STATUS": data.STATUS,
                    "ISQUERY": isqueryVal,
                    // "SERVERTYPE": data.SERVERTYPE,
                    "YEAR": data.YEAR,
                    "ZYTB": data.ZYTB
                });
            } else {
                results = sendAjax(modelURL + "resource/getResourceByGuid", "POST", {
                    guid: currentData.RESOURCEID
                });
                let data = results.data 
                for (var key in data) {
                    data = data[key];
                    break;
                }
                var isqueryVal;
                if (data.ISQUERY == "是" || data.ISQUERY == "1") {
                    isqueryVal = "是";
                } else {
                    isqueryVal = "否";
                }
                if (!onceRequestTAG) {
                    fillLayerDropdown('ipt_form_select',data);
                }
                //地图服务数据表单回显
                form.val('MapServiceBasicdataForm', {
                    "LAYERALIAS": data.LAYERALIAS,
                    // "COMPANY": data.COMPANY,
                    // "SPATIAL": data.SPATIAL,
                    // "SERVICESTYPE": data.SERVICE_CATEGORY,
                    // "RESOURCEPOSITION": data.POSITION,
                    "ADDRESS": data.ADDRESS,
                    // "ID": data.ID,
                    "STYLE": data.STYLE,
                    "POSITION": data.LAYERPOSITION,
                    "PRJ": data.PRJ,
                    "PARAMETERS": data.PARAMETERS,
                    // "SERVICETYPE": data.SERVICETYPE,
                    // "SOURCE": data.SOURCE,
                    // "STATUS": data.STATUS,
                    "ISQUERY": isqueryVal,
                    // "SERVERTYPE": data.SERVERTYPE,
                    "YEAR": data.YEAR,
                    "ZYTB": data.ZYTB
                });
            }
            if (typeof results == 'string') {
                data = JSON.parse(results).data
            } else {
                data = results.data
            }
            if (currentData.ZYLX == 1 || currentData.ZYLX == 2) { // arcgis服务 
                layer.open({
                    type: 1,
                    title: "arcgis服务详细信息",
                    shadeClose: true,
                    area:['400px','500px'],
                    content: $('#arcgisDiv'),
                    end: function (res) {
                        $("#arcgisDiv").css("display", 'none');
                    },
                    btn: ['确定'],
                    yes: function (index) {
                        layer.close(index);
                    }
                });

            } else if (currentData.ZYLX == 3) { // 服务注册
                layer.open({
                    type: 1,
                    title: "服务注册详细信息",
                    shadeClose: true,
                    area:['400px','500px'],
                    content: $('#regiesterDiv'),
                    end: function (res) {
                        $("#regiesterDiv").css("display", 'none');
                    },
                    btn: ['确定'],
                    yes: function (index) {
                        layer.close(index);
                    }
                });
            } else if (currentData.ZYLX == 4) { // 图件服务 
                layer.open({
                    type: 1,
                    title: "图件服务详细信息",
                    shadeClose: true,
                    area:['400px','500px'],
                    content: $('#mapDiv'),
                    end: function (res) {
                        $("#mapDiv").css("display", 'none');
                    },
                    btn: ['确定'],
                    yes: function (index) {
                        layer.close(index);
                    }
                });
            }
        }
    })
}
function sendAjax(url, type, data) {
    $.ajaxSettings.async = false;
    var results;
    $.ajax({
        type: type,
        dataType: "json",
        url: url,
        data: data,
        success: function (data) {
            results = data;
        },
        error: function (error) {
            results = error;
        }
    });
    return results;
}  
function saveRadio() {
    form.on('radio(jiedian)', function (data) {
        if (data.value == '通过') { 
            type = true
            statusResult = 2;
        } else if (data.value == '不通过') { 
            type = false 
            statusResult = 3
        }
    }) 
}
function getUserRole(){
    // （0  普通用户  1   部门管理员   2  系统管理员）
    var results = sendAjax(modelURL + "user/getUserIsManager", "POST", {
        userNo:portaluserno
    });
    if (results.code == 200) {
        return results.data.ISMANAGER
    } else {
        return null;
    }
}
//填充图层字段下拉框
function fillLayerDropdown(className,data) {
    var layerSelects = $("." + className);
    var oneSelect, oneSelectName, zdName, dataDict;
    for (var i = 0; i < layerSelects.length; i++) {
        oneSelect = layerSelects[i];
        oneSelectName = oneSelect.attributes.name.value;
        if (oneSelectName == "SPATIAL") {
            zdName = "spatial";
            let dataDict1= getDataDict(zdName); 
            let spatialData = dataDict1.filter (item => item.ZDVALUE == data.SPATIAL)
            $(oneSelect).empty();
            $(oneSelect).val(spatialData[0].ZDTITLE)
        } else if (oneSelectName == "SERVICESTYPE") {
            dataDict = getDataDict("serviceType"); 
            let servarData = dataDict.filter(item => item.ZDVALUE == data.SERVICE_CATEGORY)
            $(oneSelect).val(servarData[0].ZDTITLE)
        } else if (oneSelectName == "RESOURCEPOSITION") {
            var strPositionData = null;
            strPositionData = getSpecialDataDict("position");
            $(oneSelect).empty();
            let positionData = strPositionData.filter(item => item.ID == data.POSITION)
            $(oneSelect).val(positionData[0].ZDTITLE)
        } else if (oneSelectName == "COMPANY") {
            var strCompanyData = null;
            strCompanyData = getCompanyDataDict(portaluserno); 
            $(oneSelect).empty();
            $(oneSelect).val(strCompanyData.FK_DEPTTEXT)
        } else {
            zdName = "layer" + oneSelectName.toLowerCase();
            dataDict = getDataDict(zdName);
            if (zdName == 'layerservicetype') {
                dataDict.filter(item => {
                    if (item.ZDVALUE == data.SERVICETYPE) {
                        $(oneSelect).empty();
                        $(oneSelect).val(item.ZDTITLE)
                    }
                })
            } else if (zdName == 'layersource') {
                dataDict.filter(item => {
                    if (item.ZDVALUE == data.SOURCE) {
                        $(oneSelect).empty();
                        $(oneSelect).val(item.ZDTITLE)
                    }
                })
            } else if (zdName == 'layerstatus') { 
                dataDict.filter(item => {
                    if (item.ZDVALUE == data.STATUS) {
                        $(oneSelect).empty();
                        $(oneSelect).val(item.ZDTITLE)
                    }
                })
            } else if (zdName == 'layerservertype') { 
                dataDict.filter(item => {
                    if (item.ZDVALUE == data.SERVERTYPE) {
                        $(oneSelect).empty();
                        $(oneSelect).val(item.ZDTITLE)
                    }
                })
            } 
        } 
    }
    form.render();
    onceRequestTAG = true;
}